package com.qpkj.oms.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.github.pagehelper.util.StringUtil;
import com.qpkj.common.constant.TaskConstants;
import com.qpkj.common.core.domain.AjaxResult;
import com.qpkj.common.core.domain.model.LoginUser;
import com.qpkj.common.utils.DateUtils;
import com.qpkj.common.utils.SecurityUtils;
import com.qpkj.oms.domain.*;
import com.qpkj.oms.mapper.*;
import com.qpkj.oms.parameter.TaskAddVo;
import com.qpkj.oms.parameter.TaskProductVo;
import com.qpkj.oms.parameter.TaskToppingVo;
import com.qpkj.oms.result.ProductResult;
import com.qpkj.oms.result.ReceiveProductResut;
import com.qpkj.oms.result.TaskReceiveResult;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qpkj.oms.service.IOmsTaskService;
import org.springframework.transaction.annotation.Transactional;

import static com.qpkj.common.core.domain.AjaxResult.error;

/**
 * 任务Service业务层处理
 *
 * @author ruoyi
 * @date 2022-12-20
 */
@Service
public class OmsTaskServiceImpl implements IOmsTaskService {
    private static final Logger log = LoggerFactory.getLogger(OmsTaskServiceImpl.class);
    @Autowired
    private OmsTaskMapper omsTaskMapper;
    @Autowired
    private OmsComplementRecordMapper omsComplementRecordMapper;
    @Autowired
    private OmsProductCategoryMapper omsProductCategoryMapper;
    @Autowired
    private OmsProductMapper omsProductMapper;
    @Autowired
    private OmsTaskProductMapper taskProductMapper;
    @Autowired
    private OmsProductMapper productMapper;
    @Autowired
    private OmsContractMapper omsContractMapper;
    @Autowired
    private OmsProductNeedsMapper needsMapper;
    @Autowired
    private OmsTaskStepMapper stepMapper;
    @Autowired
    private OmsStockRecoderMapper stockRecoderMapper;
    @Autowired
    private OmsProductionRecoderMapper productionRecoderMapper;
    @Autowired
    private OmsAchievementMapper achievementMapper;
    @Autowired
    private OmsTaskStepMapper omsTaskStepMapper;
    @Autowired
    private OmsProductCategoryMapper categoryMapper;

    /**
     * 查询任务
     *
     * @param taskId 任务主键
     * @return 任务
     */
    @Override
    public OmsTask selectOmsTaskByTaskId(Long taskId) {
        return omsTaskMapper.selectOmsTaskByTaskId(taskId);
    }

    /**
     * 查询任务列表
     *
     * @param omsTask 任务
     * @return 任务
     */
    @Override
    public List<OmsTask> selectOmsTaskList(OmsTask omsTask) {
        List<OmsTask> taskList = omsTaskMapper.selectOmsTaskList(omsTask);
        if (!ObjectUtils.isEmpty(taskList)) {
            taskList.forEach(task -> {
                OmsTaskProduct product = new OmsTaskProduct();
                product.setTaskId(task.getTaskId());
                List<OmsTaskProduct> productList = taskProductMapper.selectOmsTaskProductList(product);
                task.setProductList(productList);
            });
        }
        return taskList;
    }

    /**
     * 查询任务列表
     *
     * @param omsTask 任务
     * @return 任务
     */
    @Override
    public List<OmsTask> selectOmsTaskListExport(OmsTask omsTask) {

        List<OmsTask> taskList = omsTaskMapper.selectOmsTaskList(omsTask);
        return taskList;
    }

    /**
     * 新增任务
     *
     * @param taskAddVo 任务
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertOmsTask(TaskAddVo taskAddVo) {
        // 库存判断

        for (int i = 0; i < taskAddVo.getProductVoList().size(); i++) {
            TaskProductVo productVo = taskAddVo.getProductVoList().get(i);
            OmsProduct product = productMapper.selectOmsProductByProductId(productVo.getProductId());
            //查生产所需
            OmsProductNeeds needs = new OmsProductNeeds();
            needs.setProductId(product.getProductId());
            List<OmsProductNeeds> needsList = needsMapper.selectOmsProductNeedsList(needs);
            for (OmsProductNeeds productNeeds : needsList) {

                //通过物料编号查询当前物料判断分类
                OmsProduct omsProduct=productMapper.selectOmsProductByProductNo(productNeeds.getProductNo());
                String categoryName = selectCategory(omsProduct.getProductCategory());
                if(categoryName.equals("原材料")){
                    if (productVo.getProductNum()*productNeeds.getProductNum() > omsProduct.getProductStock()) {
                        return AjaxResult.error("生产成品"+omsProduct.getProductName()+"库存不足！");
                    }
                }
                if(categoryName.equals("半成品")){
                    OmsProductNeeds needsTwo = new OmsProductNeeds();
                    needsTwo.setProductId(omsProduct.getProductId());
                    List<OmsProductNeeds> needsListTwo = needsMapper.selectOmsProductNeedsList(needsTwo);
                    for (OmsProductNeeds productNeedsTwo : needsListTwo){
                        OmsProduct omsProductTwo=productMapper.selectOmsProductByProductNo(productNeedsTwo.getProductNo());
                        if (productVo.getProductNum()*productNeeds.getProductNum()*productNeedsTwo.getProductNum() > omsProductTwo.getProductStock()) {
                            return AjaxResult.error("生产成品"+omsProductTwo.getProductName()+"库存不足！");
                        }
                    }
                }
            }
        }
        OmsTask omsTask = new OmsTask();
        omsTask.setCreateTime(DateUtils.getNowDate());
        omsTask.setTaskCategory(taskAddVo.getTaskCategory());
        omsTask.setCreateBy(getLoginUser().getUsername());
        omsTask.setTaskNo(getTaskNo());
        omsTask.setFinishTime(DateUtils.dateTime("yyyy-MM-dd", taskAddVo.getFinishTime()));
        omsTask.setReleaseTime(DateUtils.getNowDate());
        omsTask.setContractId(taskAddVo.getContractId());
        omsTask.setContractNo(taskAddVo.getContractNo());
        omsTask.setContractName(taskAddVo.getContractName());
        omsTask.setIsPainting(taskAddVo.getIsPainting());
        // 录入任务
        omsTaskMapper.insertOmsTask(omsTask);
        // 录入生产目标
        for (TaskProductVo productVo : taskAddVo.getProductVoList()) {
            OmsTaskProduct omsTaskProduct = new OmsTaskProduct();
            omsTaskProduct.setTaskId(omsTask.getTaskId());
            omsTaskProduct.setProductNum(productVo.getProductNum());
            omsTaskProduct.setProductId(productVo.getProductId());

            OmsProduct omsProduct = productMapper.selectOmsProductByProductId(productVo.getProductId());
            omsTaskProduct.setProductName(omsProduct.getProductName());
            omsTaskProduct.setProductImage(omsProduct.getProductImage());
            omsTaskProduct.setProductCustomer(omsProduct.getProductCustomer());
            omsTaskProduct.setProductNo(omsProduct.getProductNo());
            omsTaskProduct.setProductColour(productVo.getProductColour());
            omsTaskProduct.setProductSku(omsProduct.getProductSku());
            taskProductMapper.insertOmsTaskProduct(omsTaskProduct);
        }
        // 默认录入一条领料记录
        saveTaskStep(omsTask, TaskConstants.LINLIAO);
        // 增加生产记录
        updateProductionRecoder(1);
        return AjaxResult.success("任务发布成功！");
    }
    private String selectCategory(Long productCategory) {
        String categoryName = "";
        OmsProductCategory category = categoryMapper.selectOmsProductCategoryByCategoryId(productCategory);
        if (category.getParentId().equals(0L)) {
            // 一级分类
            categoryName = category.getCategoryName();
        } else {
            // ?
            OmsProductCategory category1 = categoryMapper.selectOmsProductCategoryByCategoryId(category.getParentId());
            categoryName = category1.getCategoryName();
        }

        return categoryName;
    }
    /**
     * 新增任务记录
     *
     * @param task
     * @param type
     */
    private void saveTaskStep(OmsTask task, String type) {
        log.debug("======================新增任务步骤======================");
        OmsTaskProduct product = new OmsTaskProduct();
        product.setTaskId(task.getTaskId());
        List<OmsTaskProduct> productList = taskProductMapper.selectOmsTaskProductList(product);
        if (!ObjectUtils.isEmpty(productList)) {
            productList.forEach(omsTaskProduct -> {
                // 如果不存在，则新增
                OmsTaskStep step = new OmsTaskStep();
                step.setTaskId(task.getTaskId());
                step.setStepType(type);
                step.setProductId(omsTaskProduct.getProductId());
                OmsTaskStep taskStep = stepMapper.selectOmsTaskStep(step);
                if (ObjectUtils.isEmpty(taskStep)) {
                    if (task.getTaskCategory().equals("1") || task.getTaskCategory().equals("2")) {
                        if (type.equals(TaskConstants.WANCHENG)) {
                            step.setOperatorName(getLoginUser().getUsername());
                            step.setStepTime(new Date());
                            step.setCanReject("0");
                        } else {
                            step.setCanReject("1");
                        }
                    } else {
                        step.setCanReject("0");
                    }
                    stepMapper.insertOmsTaskStep(step);
                } else {
                    log.debug("======================任务驳回重做========================");
                }
            });
        }
    }

    /**
     * 任务是否可以进入下一环节
     *
     * @param task
     * @param stepType 任务当前步骤
     * @return
     */
    private boolean intoNext(OmsTask task, String stepType) {
        OmsTaskStep step = new OmsTaskStep();
        step.setTaskId(task.getTaskId());
        step.setStepType(stepType);
        List<OmsTaskStep> stepList = stepMapper.selectOmsTaskStepList(step);
        for (OmsTaskStep taskStep : stepList) {
            if (taskStep.getStepStatus().equals("0") || taskStep.getStepStatus().equals("2")) {
                return false;
            }
        }
        return true;
    }

    /**
     * 修改任务
     *
     * @param omsTask 任务
     * @return 结果
     */
    @Override
    public int updateOmsTask(OmsTask omsTask) {
        omsTask.setUpdateTime(DateUtils.getNowDate());
        return omsTaskMapper.updateOmsTask(omsTask);
    }

    /**
     * 批量删除任务
     *
     * @param taskIds 需要删除的任务主键
     * @return 结果
     */
    @Override
    public int deleteOmsTaskByTaskIds(Long[] taskIds) {
        return omsTaskMapper.deleteOmsTaskByTaskIds(taskIds);
    }

    /**
     * 删除任务信息
     *
     * @param taskId 任务主键
     * @return 结果
     */
    @Override
    public int deleteOmsTaskByTaskId(Long taskId) {
        return omsTaskMapper.deleteOmsTaskByTaskId(taskId);
    }

    private String getTaskNo() {
        String s = new SimpleDateFormat("yyMMdd").format(new Date());
        System.out.println(s);
        StringBuilder str = new StringBuilder();
        str.append(s);
        Random random = new Random();
        int min = 10000000;
        int max = 99999999;
        int sum = random.nextInt(max) % (max - min + 1) + min;
        str.append(sum);
        return str.toString();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult taskTopping(TaskToppingVo taskToppingVo) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskToppingVo.getTaskId());
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在！");
        }
        if (taskToppingVo.getType() == 1) {
            task.setTaskTopping("1");
            task.setToppingTime(new Date());
        } else {
            task.setTaskTopping("0");
        }
        if (omsTaskMapper.updateOmsTask(task) > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult taskCancel(Long taskId) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在");
        }
        task.setStatus("2");
        omsTaskMapper.updateOmsTask(task);
        // 如果已经完成领料，则恢复对应的原材料库存（暂时不做，后续客户要求再放开）
       /* OmsTaskStep step = new OmsTaskStep();
        step.setTaskId(taskId);
        step.setStepType("0");
        OmsTaskStep taskStep = stepMapper.selectOmsTaskStep(step);
        if (!ObjectUtils.isEmpty(taskStep)) {
            taskStep.setDelFlag("1");
            stepMapper.updateOmsTaskStep(taskStep);
        }*/
        // 修改生产记录
        updateProductionRecoder(3);
        return AjaxResult.success("任务取消成功！");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateTaskDate(Long taskId, String time) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在");
        }
        task.setFinishTime(DateUtils.dateTime("yyyy-MM-dd", time));
        if (omsTaskMapper.updateOmsTask(task) > 0) {
            return AjaxResult.success("修改成功！");
        }
        return AjaxResult.error("修改失败");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateDeliver(Long taskId, String inputDeliver) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在");
        }
        task.setDeliver(inputDeliver);
        if (omsTaskMapper.updateOmsTask(task) > 0) {
            return AjaxResult.success("修改成功！");
        }
        return AjaxResult.error("修改失败");
    }

    @Override
    public List<TaskReceiveResult> getTaskStep(Long taskId, Integer type) {
        List<TaskReceiveResult> receiveResults = new ArrayList<>();
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            //return AjaxResult.error("任务ID不存在");
            return null;
        }
        OmsTaskStep step = new OmsTaskStep();
        step.setTaskId(taskId);
        step.setStepType(String.valueOf(type));
        step.setDelFlag("0");
        List<OmsTaskStep> stepList = stepMapper.selectOmsTaskStepList(step);
        // 如果存在被驳回的，返回空集合
        //OmsTaskStep taskStep = stepMapper.selectOmsTaskStep(step);
        if (ObjectUtils.isEmpty(stepList)) {
            return null;
        }
        // 封装返回数据
        for (OmsTaskStep taskStep : stepList) {
            Long pId = taskStep.getProductId();
            OmsTaskProduct taskProduct = new OmsTaskProduct();
            taskProduct.setTaskId(taskId);
            taskProduct.setProductId(pId);
            OmsTaskProduct omsTaskProduct = taskProductMapper.selectOmsTaskProduct(taskProduct);

            if (!ObjectUtils.isEmpty(omsTaskProduct)) {
                // 组装数据
                TaskReceiveResult result = new TaskReceiveResult();
                result.setTaskId(task.getTaskId());
                result.setDeliver(task.getDeliver());
                result.setStepId(taskStep.getStepId());
                result.setProductNmae(omsTaskProduct.getProductName());
                result.setProductNum(omsTaskProduct.getProductNum());
                result.setProductColour(omsTaskProduct.getProductColour());
                result.setProductSku(omsTaskProduct.getProductSku());
                result.setIsBuShu(task.getIsBuShu());
                result.setPushTime(DateUtils.parseDateToStr("yyyy-MM-dd", task.getReleaseTime()));
                result.setFinishDate(DateUtils.parseDateToStr("yyyy-MM-dd", task.getFinishTime()));
                if (!ObjectUtils.isEmpty(taskStep.getStepTime())) {
                    result.setCompleteTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", taskStep.getStepTime()));
                }
                result.setHandleName(taskStep.getOperatorName());
                if (!ObjectUtils.isEmpty(taskStep.getRejectTime())) {
                    result.setBackTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", taskStep.getRejectTime()));
                }
                result.setStatus(taskStep.getStepStatus());


                OmsProductNeeds needs = new OmsProductNeeds();
                needs.setProductId(omsTaskProduct.getProductId());
                List<OmsProductNeeds> needsList = needsMapper.selectOmsProductNeedsList(needs);
                if (!ObjectUtils.isEmpty(needsList)) {
                    List<ReceiveProductResut> resutList = new ArrayList<>();
                    needsList.forEach(omsProductNeeds -> {
                        ReceiveProductResut receiveProductResut = new ReceiveProductResut();
                        receiveProductResut.setProductId(omsProductNeeds.getProductId());
                        receiveProductResut.setProductName(omsProductNeeds.getProductName());
                        // 成品A*原材料
                        receiveProductResut.setProductNum(omsTaskProduct.getProductNum() + "*" + omsTaskProduct.getProductNum() * omsProductNeeds.getProductNum());
                        resutList.add(receiveProductResut);
                    });
                    result.setResutList(resutList);
                }
                result.setCanReject(taskStep.getCanReject());
                receiveResults.add(result);
            }
        }
        return receiveResults;
    }
    /**
     * 修改任务状态
     * @param taskId
     */
    private void changeTaskStaus(Long taskId) {
        List<OmsTaskStep> omsTaskStepList = omsTaskStepMapper.selectOmsTaskStepBytaskId(taskId);
        ArrayList arrayList = new ArrayList();
        if (!ObjectUtils.isEmpty(omsTaskStepList)) {
            omsTaskStepList.forEach(item -> {
                if (!item.getStepType().equals("0")) {
                    arrayList.add(item.getStepId());
                }
            });
        }
        if (!ObjectUtils.isEmpty(arrayList)) {
            int updateStepRows = omsTaskStepMapper.deleteOmsTaskStepByStepIdsOne(arrayList);
            if (updateStepRows > 0) {
                List<OmsTaskStep> omsTaskStepListTwo = omsTaskStepMapper.selectOmsTaskStepBytaskId(taskId);
                omsTaskStepListTwo.forEach(item -> {
                    if (!item.getStepStatus().equals("0")) {
                        item.setStepStatus("0");
                        omsTaskStepMapper.updateOmsTaskStep(item);
                    }
                });
            }
        }
    }

    /**
     *
     * @param productId  生产目标的物料Id
     * @param complementNum 需要补数的数量
     * @param productNum  该任务生产目标的数量
     * @param taskId  该任务的任务id
     * @param isBuShu  是否补数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult taskcomplement(Long productId, Long complementNum, Long productNum, Long taskId, String isBuShu) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在");
        }
        OmsProductNeeds omsProductNeeds =new OmsProductNeeds();
        omsProductNeeds.setProductId(productId);
        List<OmsProductNeeds> needsList =needsMapper.selectOmsProductNeedsList(omsProductNeeds);
        int saveRows=0;
        if (!ObjectUtils.isEmpty(needsList)){
            //成品任务
            if(task.getTaskCategory().equals("1")){
                for (OmsProductNeeds needs:needsList){
                    OmsProduct product1= omsProductMapper.selectOmsProductByProductId(needs.getChildId());
                    OmsProductCategory omsProductCategory =omsProductCategoryMapper.selectOmsProductCategoryByCategoryId(product1.getProductCategory());
                    String categoryName = "";
                    if (omsProductCategory.getParentId().equals(0L)) {
                        // 一级分类
                        categoryName = omsProductCategory.getCategoryName();
                    } else {
                        // ?
                        OmsProductCategory category1 = omsProductCategoryMapper.selectOmsProductCategoryByCategoryId(omsProductCategory.getParentId());
                        categoryName = category1.getCategoryName();
                    }
                    if(categoryName.equals("半成品")||categoryName.equals("原材料")){
                        int num = (int) (product1.getProductStock() - (complementNum));
                        if (num < 0) {
                            return AjaxResult.error("库存不足");
                        }
                        task.setIsBuShu(isBuShu);
                        long compnengtsNum = 0;
                        if (ObjectUtils.isEmpty(task.getCompnengtsNum())) {
                            compnengtsNum = complementNum;
                        } else {
                            compnengtsNum = task.getCompnengtsNum() + (complementNum);
                        }
                        if (!task.getTaskStep().equals("0")) {
                            task.setTaskStep("0");
                        }
                        if (!task.getStatus().equals("0")) {
                            task.setStatus("0");
                        }
                        task.setCompnengtsNum(compnengtsNum);
                        omsTaskMapper.updateOmsTask(task);
                        product1.setProductStock(num);
                        omsProductMapper.updateOmsProduct(product1);
                        long changeNum = (complementNum * productNum);
                        OmsContract omsContract = omsContractMapper.selectOmsContractById(task.getContractId());
                        //改变生产步骤
                        changeTaskStaus(taskId);
                        //新增补数记录
                        saveRows=saveOmsComplementRecord(taskId,changeNum,product1,omsContract);
                    }
                }
            }
            //半成品生产任务
            if(task.getTaskCategory().equals("2")){
                for (OmsProductNeeds needs:needsList){
                    OmsProduct product1= omsProductMapper.selectOmsProductByProductId(needs.getChildId());
                    OmsProductCategory omsProductCategory =omsProductCategoryMapper.selectOmsProductCategoryByCategoryId(product1.getProductCategory());
                    String categoryName = "";
                    if (omsProductCategory.getParentId().equals(0L)) {
                        // 一级分类
                        categoryName = omsProductCategory.getCategoryName();
                    } else {
                        // ?
                        OmsProductCategory category1 = omsProductCategoryMapper.selectOmsProductCategoryByCategoryId(omsProductCategory.getParentId());
                        categoryName = category1.getCategoryName();
                    }
                    if(categoryName.equals("原材料")){
                        int num = (int) (product1.getProductStock() - (complementNum));
                        if (num < 0) {
                            return AjaxResult.error("库存不足");
                        }
                        task.setIsBuShu(isBuShu);
                        long compnengtsNum = 0;
                        if (ObjectUtils.isEmpty(task.getCompnengtsNum())) {
                            compnengtsNum = complementNum;
                        } else {
                            compnengtsNum = task.getCompnengtsNum() + (complementNum);
                        }
                        if (!task.getTaskStep().equals("0")) {
                            task.setTaskStep("0");
                        }
                        if (!task.getStatus().equals("0")) {
                            task.setStatus("0");
                        }
                        task.setCompnengtsNum(compnengtsNum);
                        omsTaskMapper.updateOmsTask(task);
                        product1.setProductStock(num);
                        omsProductMapper.updateOmsProduct(product1);
                        long changeNum = (complementNum * productNum);
                        OmsContract omsContract = omsContractMapper.selectOmsContractById(task.getContractId());
                        //改变生产步骤
                        changeTaskStaus(taskId);
                        //新增补数记录
                        saveRows=saveOmsComplementRecord(taskId,changeNum,product1,omsContract);
                    }
                }
            }
            //半成品包装任务
            if(task.getTaskCategory().equals("3")){
                for (OmsProductNeeds needs:needsList){
                    OmsProduct product1= omsProductMapper.selectOmsProductByProductId(needs.getChildId());
                    OmsProductCategory omsProductCategory =omsProductCategoryMapper.selectOmsProductCategoryByCategoryId(product1.getProductCategory());
                    String categoryName = "";
                    if (omsProductCategory.getParentId().equals(0L)) {
                        // 一级分类
                        categoryName = omsProductCategory.getCategoryName();
                    } else {
                        // ?
                        OmsProductCategory category1 = omsProductCategoryMapper.selectOmsProductCategoryByCategoryId(omsProductCategory.getParentId());
                        categoryName = category1.getCategoryName();
                    }
                    if(categoryName.equals("半成品")){
                        int num = (int) (product1.getProductStock() - (complementNum));
                        if (num < 0) {
                            return AjaxResult.error("库存不足");
                        }
                        task.setIsBuShu(isBuShu);
                        long compnengtsNum = 0;
                        if (ObjectUtils.isEmpty(task.getCompnengtsNum())) {
                            compnengtsNum = complementNum;
                        } else {
                            compnengtsNum = task.getCompnengtsNum() + (complementNum);
                        }
                        if (!task.getTaskStep().equals("0")) {
                            task.setTaskStep("0");
                        }
                        if (!task.getStatus().equals("0")) {
                            task.setStatus("0");
                        }
                        task.setCompnengtsNum(compnengtsNum);
                        omsTaskMapper.updateOmsTask(task);
                        product1.setProductStock(num);
                        omsProductMapper.updateOmsProduct(product1);
                        long changeNum = (complementNum * productNum);
                        OmsContract omsContract = omsContractMapper.selectOmsContractById(task.getContractId());
                        //改变生产步骤
                        changeTaskStaus(taskId);
                        //新增补数记录
                        saveRows= saveOmsComplementRecord(taskId,changeNum,product1,omsContract);
                    }
                }
            }
        }else{
            return error("生产所需不存在！");
        }
        if(saveRows>0){
            return AjaxResult.success("操作成功");
        }else{
            return AjaxResult.error("操作异常");
        }
    }
    public int saveOmsComplementRecord(Long taskId,Long changeNum,OmsProduct product1, OmsContract omsContract) {
        OmsComplementRecord omsComplementRecord = new OmsComplementRecord();
        omsComplementRecord.setTaskId(taskId);
        omsComplementRecord.setChangeNum(changeNum);
        omsComplementRecord.setContractNo(omsContract.getContractNo());
        omsComplementRecord.setContractName(omsContract.getContractName());
        omsComplementRecord.setProductName(product1.getProductName());
        omsComplementRecord.setProductNo(product1.getProductNo());
        omsComplementRecord.setProductSku(product1.getProductSku());
        omsComplementRecord.setProductColour(product1.getProductColour());
        omsComplementRecord.setCreateTime(new Date());
        return omsComplementRecordMapper.insertOmsComplementRecord(omsComplementRecord);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult taskOperation(Long taskId, Long stepId, Integer type) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在");
        }
        String taskStatus = task.getStatus();
        if (taskStatus.equals("2")) {
            return AjaxResult.error("该任务已取消");
        }
        OmsTaskStep omsTaskStep = stepMapper.selectOmsTaskStepByStepId(stepId);
        if (ObjectUtils.isEmpty(omsTaskStep)) {
            return AjaxResult.error("任务步骤不存在");
        }
        if (type == 1) {
            // 车间完成
            log.debug("======================完成任务步骤======================");
            omsTaskStep.setStepStatus("1");
            omsTaskStep.setStepTime(new Date());
            omsTaskStep.setUserId(getLoginUser().getUserId());
            omsTaskStep.setOperatorName(getLoginUser().getUsername());
            // 如果当前任务步骤是被驳回的，这里修改任务是否被驳回的状态值
            if (omsTaskStep.getStepStatus().equals("2")) {
                task.setTaskBack("0");
            }
            stepMapper.updateOmsTaskStep(omsTaskStep);
            // 生成下一个任务步骤
            // 按照任务类型进行划分
            if (task.getTaskCategory().equals("1")) {
                // 订单成品生产
                // 插球-电镀-彩绘-包装-完成
                if (omsTaskStep.getStepType().equals(TaskConstants.LINLIAO)) {
                    if(StringUtil.isEmpty(task.getIsBuShu())){
                        // 领料——减少拆解后的物料库存
                        chanageProductStock(task, omsTaskStep.getProductId());
                    }
                    // 是否可以进入下一步（全部完成才能进入下一步）
                    if (intoNext(task, TaskConstants.LINLIAO)) {
                        // 新增擦球记录
                        saveTaskStep(task, TaskConstants.CAQIU);
                        // 完成领料，修改任务步骤
                        task.setTaskStep(TaskConstants.CAQIU);
                    }
                } else if (omsTaskStep.getStepType().equals(TaskConstants.CAQIU)) {
                    // 新增电镀记录
                    if (intoNext(task, TaskConstants.CAQIU)) {
                        saveTaskStep(task, TaskConstants.DIANDU);
                        task.setTaskStep(TaskConstants.DIANDU);
                    }
                } else if (omsTaskStep.getStepType().equals(TaskConstants.DIANDU)) {
                    // 新增彩绘记录
                    if (intoNext(task, TaskConstants.DIANDU)) {
                        int paintin = Integer.parseInt(task.getIsPainting());
                        //判断是否需要彩绘
                        if (paintin == 0) {
                            saveTaskStep(task, TaskConstants.BAOZHUANG);
                            task.setTaskStep(TaskConstants.BAOZHUANG);
                        } else {
                            saveTaskStep(task, TaskConstants.CAIHUI);
                            task.setTaskStep(TaskConstants.CAIHUI);
                        }
                    }
                } else if (omsTaskStep.getStepType().equals(TaskConstants.CAIHUI)) {
                    // 新增包装记录
                    if (intoNext(task, TaskConstants.CAIHUI)) {
                        saveTaskStep(task, TaskConstants.BAOZHUANG);
                        task.setTaskStep(TaskConstants.BAOZHUANG);
                    }
                } else if (omsTaskStep.getStepType().equals(TaskConstants.BAOZHUANG)) {
                    // 新增完成记录
                    // 修改任务状态
                    addProductStock(task, omsTaskStep.getProductId());
                    if (intoNext(task, TaskConstants.BAOZHUANG)) {
                        task.setStatus("1");
                        task.setCompleteDate(new Date());
                        saveTaskStep(task, TaskConstants.WANCHENG);
                        updateProductionRecoder(2);
                        task.setTaskStep(TaskConstants.WANCHENG);
                    }
                }
                // 修改任务步骤状态
                task.setProgressTime(new Date());
                omsTaskMapper.updateOmsTask(task);
            } else if (task.getTaskCategory().equals("2")) {
                // 备货半成品生产
                // 插球-电镀-彩绘-完成
                if (omsTaskStep.getStepType().equals(TaskConstants.LINLIAO)) {
                    if(StringUtil.isEmpty(task.getIsBuShu())){
                        // 领料——减少拆解后的物料库存
                        chanageProductStock(task, omsTaskStep.getProductId());
                    }
                    if (intoNext(task, TaskConstants.LINLIAO)) {
                        // 新增擦球记录
                        saveTaskStep(task, TaskConstants.CAQIU);
                        // task.setStatus(TaskConstants.CAQIU);
                        task.setTaskStep(TaskConstants.CAQIU);
                    }
                } else if (omsTaskStep.getStepType().equals(TaskConstants.CAQIU)) {
                    // 新增电镀记录
                    if (intoNext(task, TaskConstants.CAQIU)) {
                        saveTaskStep(task, TaskConstants.DIANDU);
                        // task.setStatus(TaskConstants.DIANDU);
                        task.setTaskStep(TaskConstants.DIANDU);
                    }
                } else if (omsTaskStep.getStepType().equals(TaskConstants.DIANDU)) {
                    // 新增彩绘记录
                    if (intoNext(task, TaskConstants.DIANDU)) {
                        String paintin = task.getIsPainting();
                        if (paintin.equals("0")) {
                            // 新增完成记录
                            addProductStock(task, omsTaskStep.getProductId());
                            task.setStatus("1");
                            task.setCompleteDate(new Date());
                            saveTaskStep(task, TaskConstants.WANCHENG);
                            //修改生产记录
                            updateProductionRecoder(2);
                            task.setTaskStep(TaskConstants.WANCHENG);
                        } else {
                            saveTaskStep(task, TaskConstants.CAIHUI);
                            //task.setStatus(TaskConstants.CAIHUI);
                            task.setTaskStep(TaskConstants.CAIHUI);
                        }

                    }
                } else if (omsTaskStep.getStepType().equals(TaskConstants.CAIHUI)) {
                    // 新增完成记录
                    addProductStock(task, omsTaskStep.getProductId());
                    if (intoNext(task, TaskConstants.CAIHUI)) {
                        task.setStatus("1");
                        task.setCompleteDate(new Date());
                        saveTaskStep(task, TaskConstants.WANCHENG);
                        updateProductionRecoder(2);
                        task.setTaskStep(TaskConstants.WANCHENG);
                    }
                }
                task.setProgressTime(new Date());
                omsTaskMapper.updateOmsTask(task);
            } else {
                // 备货半成品包装
                // 包装-完成
                if (omsTaskStep.getStepType().equals(TaskConstants.LINLIAO)) {
                    if(StringUtil.isEmpty(task.getIsBuShu())){
                        // 领料——减少拆解后的物料库存
                        chanageProductStock(task, omsTaskStep.getProductId());
                    }
                    if (intoNext(task, TaskConstants.LINLIAO)) {
                        saveTaskStep(task, TaskConstants.BAOZHUANG);
                        task.setTaskStep(TaskConstants.BAOZHUANG);
                    }
                } else {
                    addProductStock(task, omsTaskStep.getProductId());
                    if (intoNext(task, TaskConstants.BAOZHUANG)) {
                        saveTaskStep(task, TaskConstants.WANCHENG);
                        task.setStatus("1");
                        task.setCompleteDate(new Date());
                        //修改生产记录
                        updateProductionRecoder(2);
                        task.setTaskStep(TaskConstants.WANCHENG);
                    }
                }
                task.setProgressTime(new Date());
                omsTaskMapper.updateOmsTask(task);
            }
        } else {
            // 驳回
            log.debug("======================驳回任务步骤======================");
            rejectTask(task, omsTaskStep);
            /*if (task.getTaskCategory().equals("1")) {
                task.setTaskStep(String.valueOf(Integer.parseInt(task.getTaskStep()) - 1));
            } else if (task.getTaskCategory().equals("2")) {
                //
            }*/
            task.setTaskStep(String.valueOf(Integer.parseInt(task.getTaskStep()) - 1));
            // 任务回滚
            task.setTaskBack("1");
            task.setProgressTime(new Date());
            omsTaskMapper.updateOmsTask(task);
        }
        return AjaxResult.success("操作成功！");
    }

    /**
     * 领料环节完成，减少库存
     *
     * @param task
     */
    private void chanageProductStock(OmsTask task, Long productId) {
        log.debug("======================库存变动======================");
        //OmsProduct product = productMapper.selectOmsProductByProductId(productId);
        OmsTaskProduct taskProduct = new OmsTaskProduct();
        taskProduct.setTaskId(task.getTaskId());
        taskProduct.setProductId(productId);
        OmsTaskProduct product = taskProductMapper.selectOmsTaskProduct(taskProduct);
        if (!ObjectUtils.isEmpty(product)) {
            //备货半成品生产
            if(task.getTaskCategory().equals("2")){
                OmsProduct productTwo= productMapper.selectOmsProductByProductId(product.getProductId());
//                int num = product.getProductNum();
//                productTwo.setProductStock(productTwo.getProductStock() - num);
//                productTwo.setUpdateTime(new Date());
//                productMapper.updateOmsProduct(productTwo);
//                addStockRecoder(task, productTwo, product.getProductNum(), 0, "领料", getLoginUser().getUsername());
                OmsProductNeeds needsTwo = new OmsProductNeeds();
                needsTwo.setProductId(productTwo.getProductId());
                List<OmsProductNeeds> needsListTwo = needsMapper.selectOmsProductNeedsList(needsTwo);
                if(!ObjectUtils.isEmpty(needsListTwo)){
                    needsListTwo.forEach(omsProductNeedsTwo -> {
                        OmsProduct productThree = productMapper.selectOmsProductByProductNo(omsProductNeedsTwo.getProductNo());
                      //修改原材料库存
                        int numTwo=product.getProductNum() * omsProductNeedsTwo.getProductNum();
                        productThree.setProductStock(productThree.getProductStock()-numTwo);
                        productThree.setUpdateTime(new Date());
                        productMapper.updateOmsProduct(productThree);
                        addStockRecoder(task, productThree, product.getProductNum()* omsProductNeedsTwo.getProductNum(), 0, "领料", getLoginUser().getUsername());
                    });
                }
            }else{
                //订单成品生产或者备货半成品包装
                OmsProduct product1 = productMapper.selectOmsProductByProductId(product.getProductId());
                //修改成品库存
//                int num = product.getProductNum();
//                product1.setProductStock(product1.getProductStock() - num);
//                product1.setUpdateTime(new Date());
//                productMapper.updateOmsProduct(product1);
//                addStockRecoder(task, product1, product.getProductNum(), 0, "领料", getLoginUser().getUsername());
                OmsProductNeeds needs = new OmsProductNeeds();
                needs.setProductId(product1.getProductId());
                List<OmsProductNeeds> needsList = needsMapper.selectOmsProductNeedsList(needs);
                if(!ObjectUtils.isEmpty(needsList)){
                    needsList.forEach(omsProductNeeds -> {
                        OmsProduct productFour = productMapper.selectOmsProductByProductNo(omsProductNeeds.getProductNo());
                        //修改半成品库存
                        int numFour = product.getProductNum() * omsProductNeeds.getProductNum();
                        productFour.setProductStock(productFour.getProductStock() - numFour);
                        productFour.setUpdateTime(new Date());
                        productMapper.updateOmsProduct(productFour);
                        addStockRecoder(task, productFour, product.getProductNum() * omsProductNeeds.getProductNum(), 0, "领料", getLoginUser().getUsername());
                        //再通过半成品物料ID查询生产所需
                        OmsProductNeeds needsSix = new OmsProductNeeds();
                        needsSix.setProductId(productFour.getProductId());
                        List<OmsProductNeeds> needsListSix = needsMapper.selectOmsProductNeedsList(needsSix);
                        if(!ObjectUtils.isEmpty(needsListSix)){
                            needsListSix.forEach(omsProductNeedsSix -> {
                                OmsProduct productSix = productMapper.selectOmsProductByProductNo(omsProductNeedsSix.getProductNo());
                                //修改原材料库存
                                int numSix = product.getProductNum() * omsProductNeeds.getProductNum() * omsProductNeedsSix.getProductNum();
                                productSix.setProductStock(productSix.getProductStock() - numSix);
                                productSix.setUpdateTime(new Date());
                                productMapper.updateOmsProduct(productSix);
                                addStockRecoder(task, productSix, product.getProductNum() * omsProductNeeds.getProductNum() * omsProductNeedsSix.getProductNum(), 0, "领料", getLoginUser().getUsername());
                            });
                        }
                    });
                }
            }
        }
    }

    private void addProductStock(OmsTask task, Long productId) {
        OmsTaskProduct taskProduct = new OmsTaskProduct();
        taskProduct.setProductId(productId);
        taskProduct.setTaskId(task.getTaskId());
        OmsTaskProduct product = taskProductMapper.selectOmsTaskProduct(taskProduct);
        if (!ObjectUtils.isEmpty(product)) {
            OmsProduct omsProduct = productMapper.selectOmsProductByProductId(product.getProductId());
            if (!ObjectUtils.isEmpty(omsProduct)) {
                omsProduct.setProductStock(omsProduct.getProductStock() + product.getProductNum());
                productMapper.updateOmsProduct(omsProduct);
                addStockRecoder(task, omsProduct, product.getProductNum(), 1, "完成成品生产新增库存", getLoginUser().getUsername());
            }
        }
    }

    /**
     * 任务驳回
     *
     * @param task
     * @param step
     */
    private void rejectTask(OmsTask task, OmsTaskStep step) {
        OmsTaskStep omsTaskStep = new OmsTaskStep();
        omsTaskStep.setStepType(String.valueOf(Integer.parseInt(step.getStepType()) - 1));
        omsTaskStep.setTaskId(task.getTaskId());
        omsTaskStep.setProductId(step.getProductId());
        OmsTaskStep taskStep = stepMapper.selectOmsTaskStep(omsTaskStep);
        if (!ObjectUtils.isEmpty(taskStep)) {
            taskStep.setStepStatus("2");
            taskStep.setRejectTime(new Date());
            stepMapper.updateOmsTaskStep(taskStep);
        }
    }

    @Override
    public AjaxResult taskProductList(Long taskId) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在");
        }
        List<OmsProductNeeds> productNeedsList = new ArrayList<>();
        OmsTaskProduct product = new OmsTaskProduct();
        product.setTaskId(taskId);
        List<OmsTaskProduct> productList = taskProductMapper.selectOmsTaskProductList(product);
        if (!ObjectUtils.isEmpty(productList)) {
            productList.forEach(omsTaskProduct -> {
                OmsProductNeeds needs = new OmsProductNeeds();
                needs.setProductId(omsTaskProduct.getProductId());
                List<OmsProductNeeds> needsList = needsMapper.selectOmsProductNeedsList(needs);
                if (!ObjectUtils.isEmpty(needsList)) {
                    productNeedsList.addAll(needsList);
                }
            });
        }
        return AjaxResult.success(productNeedsList);
    }

    public AjaxResult taskContract(Long taskId) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在");
        }
        OmsContract omsContract = omsContractMapper.selectOmsContractById(task.getContractId());
        return AjaxResult.success(omsContract.getContractName());
    }

    @Override
    public AjaxResult taskAllProductList(Long taskId) {
        OmsTask task = omsTaskMapper.selectOmsTaskByTaskId(taskId);
        if (ObjectUtils.isEmpty(task)) {
            return AjaxResult.error("任务ID不存在");
        }
        OmsTaskProduct product = new OmsTaskProduct();
        product.setTaskId(taskId);
        return AjaxResult.success(taskProductMapper.selectOmsTaskProductList(product));
    }

    private void addStockRecoder(OmsTask task, OmsProduct product, int num, int type, String reson, String operPerson) {
        OmsStockRecoder recoder = new OmsStockRecoder();
        recoder.setRecoderDate(new Date());
        recoder.setRecoderName(product.getProductName());
        recoder.setRecoderNo(product.getProductNo());
        recoder.setRecoderSku(product.getProductSku());
        recoder.setCategoryName(product.getCategory().getCategoryName());
        recoder.setColour(product.getProductColour());
        if (type == 1) {
            recoder.setRecoderChanage("+" + num);
        } else {
            recoder.setRecoderChanage("-" + num);
        }
        recoder.setRecoderReason(reson);
        recoder.setRecoderOpter(operPerson);
        recoder.setTaskNo(task.getTaskNo());
        stockRecoderMapper.insertOmsStockRecoder(recoder);
    }

    /**
     * 修改生产记录
     *
     * @param type 1创建任务；2完成任务；3取消任务
     */
    private void updateProductionRecoder(int type) {
        OmsProductionRecoder recoder = productionRecoderMapper.selectOmsProductionRecoderByDate(new Date());
        if (type == 1) {
            if (ObjectUtils.isEmpty(recoder)) {
                OmsProductionRecoder productionRecoder = new OmsProductionRecoder();
                productionRecoder.setProductionDate(new Date());
                productionRecoder.setProductionAddnum(1);
                productionRecoder.setProductionFinishnum(0);
                productionRecoder.setProductionIncompletenum(1);
                productionRecoderMapper.insertOmsProductionRecoder(productionRecoder);
            } else {
                recoder.setProductionAddnum(recoder.getProductionAddnum() + 1);
                recoder.setProductionIncompletenum(recoder.getProductionIncompletenum() + 1);
                productionRecoderMapper.updateOmsProductionRecoder(recoder);
            }
        } else if (type == 2) {
            recoder.setProductionFinishnum(recoder.getProductionFinishnum() + 1);
            recoder.setProductionIncompletenum(recoder.getProductionIncompletenum() - 1);
            productionRecoderMapper.updateOmsProductionRecoder(recoder);
        } else if (type == 3) {
            recoder.setProductionAddnum(recoder.getProductionAddnum() - 1);
            recoder.setProductionIncompletenum(recoder.getProductionIncompletenum() - 1);
            productionRecoderMapper.updateOmsProductionRecoder(recoder);
        }
    }

    /**
     * 获取用户缓存信息
     */
    public LoginUser getLoginUser() {
        return SecurityUtils.getLoginUser();
    }

    @Override
    public List<OmsTaskProduct> getTaskProductListByTaskId(Long taskId) {
        OmsTaskProduct product = new OmsTaskProduct();
        product.setTaskId(taskId);
        return taskProductMapper.selectOmsTaskProductList(product);
    }

    @Override
    public List<OmsProductNeeds> getTaskProductNeedsListByTaskId(Long taskId) {
        List<OmsProductNeeds> needsList = new ArrayList<>();
        OmsTaskProduct product = new OmsTaskProduct();
        product.setTaskId(taskId);
        List<OmsTaskProduct> taskProductList = taskProductMapper.selectOmsTaskProductList(product);
        taskProductList.forEach(taskProduct -> {
            OmsProductNeeds needs = new OmsProductNeeds();
            needs.setProductId(taskProduct.getProductId());
            List<OmsProductNeeds> productNeedsList = needsMapper.selectOmsProductNeedsList(needs);
            needsList.addAll(productNeedsList);
        });
        return needsList;
    }

    public OmsProduct taskcomplement(Long productId) {
        return omsProductMapper.selectOmsProductByProductId(productId);
    }

    @Override
    public List<OmsAchievement> queryTaskAchievement(Long taskId, String achievementWorkshop) {
        OmsAchievement achievement = new OmsAchievement();
        achievement.setTaskId(taskId);
        if (!ObjectUtils.isEmpty(achievementWorkshop)) {
            achievement.setAchievementWorkshop(achievementWorkshop);
        }
        return achievementMapper.selectOmsAchievementList(achievement);
    }


}
